<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="基金/股票名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入基金/股票名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="股票或基金代码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入股票或基金代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['money:fund:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['money:fund:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['money:fund:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['money:fund:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id"/>
      <el-table-column label="基金/股票名字" align="center" prop="name"/>
      <el-table-column label="股票或基金代码" align="center" prop="code"/>
      <el-table-column label="数据更新日期" align="center" prop="updateDay"/>
      <el-table-column label="数据获取连接" align="center" class="success">
        <template slot-scope="scope">
          <el-link type="primary" target="_blank" success :href="scope.row.dataUrl"> {{scope.row.dataUrl}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['money:fund:edit']"
          >同步
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="importDate(scope.row)"
            v-hasPermi="['money:fund:edit']"
          >导入
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['money:fund:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['money:fund:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改基金/股票管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="基金/股票名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入基金/股票名字"/>
        </el-form-item>
        <el-form-item label="股票或基金代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入股票或基金代码"/>
        </el-form-item>
        <el-form-item label="数据获取连接" prop="dataUrl">
          <el-input v-model="form.dataUrl" placeholder="请输入数据获取连接"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="importTitle" :visible.sync="importShow" width="500px" append-to-body>
      <el-upload
        :action="uploadUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="1"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :show-file-list="true"
        :headers="headers"
        multiple
        class="upload-file-uploader"
        ref="upload"
      >
        <!-- 上传按钮 -->
        <el-button size="mini" type="primary">选取文件</el-button>
        <!-- 上传提示 -->
        <div class="el-upload__tip" slot="tip" v-if="showTip">
          请上传
          <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>

  import {listFund, getFund, delFund, addFund, updateFund, exportFund} from "@/api/money/fund";
  import {getToken} from "@/utils/auth";

  export default {
    name: "Fund",
    components: {},
    pros: {
      isShowTip: {
        type: Boolean,
        default: true
      },
      fileSize: {
        type: Number,
        default: 5,
      },
      fileType: {
        type: Array,
        default: () => ["cvs", "xls", "xlsx", "txt", "pdf"],
      },
    },
    data() {
      return {
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/money/fund/upload?fundId=", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        selectId:0,
        fileList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 基金/股票管理表格数据
        fundList: [],
        // 弹出层标题
        title: "",
        importTitle: "",
        // 是否显示弹出层
        open: false,
        importShow: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          code: null,
          dataUrl: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {required: true, message: "基金/股票名字不能为空", trigger: "blur"}
          ],
          code: [
            {required: true, message: "股票或基金代码不能为空", trigger: "blur"}
          ],
          dataUrl: [
            {required: true, message: "数据获取连接不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "创建时间不能为空", trigger: "blur"}
          ],
          updateTime: [
            {required: true, message: "更新时间不能为空", trigger: "blur"}
          ]
        }
      };
    },
    computed: {
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
      uploadUrl(){
      return this.uploadFileUrl + this.selectId
      },
    },

    created() {
      this.getList();
    },
    methods: {
      /** 查询基金/股票管理列表 */
      getList() {
        this.loading = true;
        listFund(this.queryParams).then(response => {
          this.fundList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          code: null,
          dataUrl: null,
          createTime: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加基金/股票管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getFund(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改基金/股票管理";
        });
      },
      /** 修改按钮操作 */
      importDate(row) {
        this.importShow = true;
        this.importTitle = row.name;
        this.selectId = row.id;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateFund(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addFund(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除基金/股票管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delFund(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有基金/股票管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportFund(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        // 校检文件类型
        if (this.fileType) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          const isTypeOk = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
          if (!isTypeOk) {
            this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
            return false;
          }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        return true;
      },
      // 文件个数超出
      handleExceed() {
        this.$message.error(`只允许上传单个文件`);
      },
      // 上传失败
      handleUploadError(err) {
        this.$message.error("上传失败, 请重试");
      },
      // 上传成功回调
      handleUploadSuccess(res, file) {
        this.$message.success("上传成功");
        this.$emit("input", res.url);
      },
      // 删除文件

      // 获取文件名称
      getFileName(name) {
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
        } else {
          return "";
        }
      }
    },

  };
</script>
